package com.gxgeek.weixin.common.util;

import com.alibaba.fastjson.JSON;
import com.gxgeek.weixin.domain.dto.*;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import static com.gxgeek.weixin.domain.enums.Constant.*;

/**
 * Created by gx on 2017/4/19.
 */
@Slf4j
public class WeixinUtil {

//    public static final String APPID = "wxfc278dba19364b72";
//    public static final String APPSECRET = "8b9d352b8f4c1c064acdc609367ff4a2";
    public static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    private static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
    //测试账号
    public static final String APPID = "wx7e3b023419fc6b74";
    public static final String APPSECRET = "61d1b3dbf35403ee14e1a641a9a040cf";


    /**
     * 获取AccessToken
     * @return
     */
    public static AccessToken getAccessToken(){
        String url = ACCESS_TOKEN_URL.replace("APPID",APPID).replace("APPSECRET",APPSECRET);
        String json =HttpClientUtil.getInstance().sendHttpsGet(url);
        return JSON.parseObject(json,AccessToken.class);
    }


    /**
     * 设置菜单案例
     * @return
     */
    public static Menu initMenu(){
        //一级菜单
        ClickButton clickButton = new ClickButton();
        clickButton.setType(BUTTON_TYPE_CLICK);
        clickButton.setKey("V1001_TODAY_MUSIC");
        clickButton.setName("点击菜单");

        //一级菜单
        ViewButton viewButton = new ViewButton();
        viewButton.setName("view 菜单");
        viewButton.setType(BUTTON_TYPE_VIEW);
        viewButton.setUrl("http://www.imooc.com");

        //扫码
        ClickButton clickButton1  = new ClickButton();
        clickButton1.setType(BUTTON_TYPE_SCANCODE_PUSH);
        clickButton1.setName("扫码示例");
        clickButton1.setKey("rselfmenu_0_1");
        clickButton1.setSub_button(new ArrayList<>());
        //上报地理位置
        ClickButton clickButton2  = new ClickButton();
        clickButton2.setType(BUTTON_TYPE_LOCATION_SELECT);
        clickButton2.setKey("rselfmenu_0_1");
        clickButton2.setName("地理位置");

        Button button = new Button();
        button.setName("其余菜单");
        button.setSub_button(Arrays.asList(clickButton1,clickButton2));

        Menu menu = new Menu();
        menu.setButton(Arrays.asList(clickButton,viewButton,button));

        return menu;
    }


    /**
     * 创建菜单
     * @param token
     * @param menu
     * @return
     */
    public static  int creatMenu(String token,String menu){
        log.info(menu);
        String url = WEIXIN_CREATMENU_URL.replace("ACCESS_TOKEN", token);
        String json = HttpClientUtil.getInstance().sendHttpPost(url,menu);
        AccessToken accessToken = JSON.parseObject(json,AccessToken.class);
        if (accessToken.getErrcode() == 0){
            log.error(json);
            return 0;
        }
        log.error(json);
        return 1;
    }


    /**
     * 查询菜单接口
     * @param token
     * @return
     */
    public static String queryMenu(String token){
        String url = WEIXIN_QUERYMENU_URL.replace("ACCESS_TOKEN", token);
        String json = HttpClientUtil.getInstance().sendHttpPost(url);
        HashMap accessToken = JSON.parseObject(json,HashMap.class);
        return json;
    }
    /**
     * 查询菜单接口
     * @param token
     * @return
     */
    public static String delMenu(String token){
        String url = WEIXIN_DELETE_MENU_URL.replace("ACCESS_TOKEN", token);
        String json = HttpClientUtil.getInstance().sendHttpPost(url);
        HashMap accessToken = JSON.parseObject(json,HashMap.class);
        return json;
    }












    public static String upload(String filePath, String accessToken,String type) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
        File file = new File(filePath);
        if (!file.exists() || !file.isFile()) {
            throw new IOException("文件不存在");
        }

        String url = UPLOAD_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE",type);

        URL urlObj = new URL(url);
        //连接
        HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();

        con.setRequestMethod("POST");
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);

        //设置请求头信息
        con.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Charset", "UTF-8");

        //设置边界
        String BOUNDARY = "----------" + System.currentTimeMillis();
        con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

        StringBuilder sb = new StringBuilder();
        sb.append("--");
        sb.append(BOUNDARY);
        sb.append("\r\n");
        sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
        sb.append("Content-Type:application/octet-stream\r\n\r\n");

        byte[] head = sb.toString().getBytes("utf-8");

        //获得输出流
        OutputStream out = new DataOutputStream(con.getOutputStream());
        //输出表头
        out.write(head);

        //文件正文部分
        //把文件已流文件的方式 推入到url中
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) != -1) {
            out.write(bufferOut, 0, bytes);
        }
        in.close();

        //结尾部分
        byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");//定义最后数据分隔线

        out.write(foot);

        out.flush();
        out.close();

        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = null;
        String result = null;
        try {
            //定义BufferedReader输入流来读取URL的响应
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            if (result == null) {
                result = buffer.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
        }

        Map <String,String>jsonObj = JSON.parseObject(result, HashMap.class);
        System.out.println(jsonObj);
        String typeName = "media_id";
        if(!"image".equals(type)){
            typeName = type + "_media_id";
        }
        String mediaId = jsonObj.get(typeName);
        return mediaId;
    }
}

